'use strict'
const path = require('path')
const defaultSettings = require('./src/settings.js')
// gzip压缩
const CompressionWebpackPlugin = require('compression-webpack-plugin')
const isProcution = function() {
  return process.env.NODE_ENV === 'poduction'
}
const isNotDev = function() {
  return process.env.NODE_ENV !== 'development'
}

function resolve(dir) {
  return path.join(__dirname, dir)
}
// // 引入等比适配插件
// const px2rem = require('postcss-px2rem')
 
// // 配置基本大小
// const postcss = px2rem({
//   // 基准大小 baseSize，需要和rem.js中相同
//   // remUnit: 14 代表 1rem = 14px; 所以当你一个14px值时，它会自动转成 (14px/14)rem
//   remUnit: 14
// })

const name = defaultSettings.title || 'vue Admin Template' // page title
// If your port is set to 80,
// use administrator privileges to execute the command line.
// For example, Mac: sudo npm run
const port = 9528 // dev port

// All configuration item explanations can be find in https://cli.vuejs.org/config/
module.exports = {
  /**
   * You will need to set publicPath if you plan to deploy your site under a sub path,
   * for example GitHub Pages. If you plan to deploy your site to https://foo.github.io/bar/,
   * then publicPath should be set to "/bar/".
   * In most cases please use '/' !!!
   * Detail: https://cli.vuejs.org/config/#publicpath
   */
  publicPath: './',
  outputDir: 'consumptionForecast',
  assetsDir: './static',
  lintOnSave: process.env.NODE_ENV === 'development',
  // lintOnSave: true,
  productionSourceMap: false,
  devServer: {
    port: port,
    open: false,
    overlay: {
      warnings: false,
      errors: false
    },
//  css: {
//     loaderOptions: {
//       less: {
//         javascriptEnabled: true,
//       },
//       postcss: {
//         plugins: [
//           postcss,
//         ],
//       },
//     },
//   },
    proxy: {
      '/api/': {
        ws: false,
        // target: 'http://127.0.0.1:8762/social/',
        //  target: 'http://127.0.0.1:8762/social/',
        // target: 'http://192.168.33.140:8762/social/', //慧企
        // target:'http://123.138.37.37:31024/social/',
        // target:'http://123.138.37.37:31005/api/',
        // target: 'http://192.168.138.54:10010/',
        target: 'http://127.0.0.1:8089/',
        // target:'http://10.192.90.119:10010/',
        changeOrigin: true,
        pathRewrite: {
          '^/api': ''
        }
      }
    },
    after: require('./mock/mock-server.js')
  },
  css: {
    loaderOptions: {
      sass: {
        // 全局导入scss变量
        // data: `@import "@/styles/variables.scss";`
      }
    }
  },
  configureWebpack: (config) => {
    if (isNotDev()) {
      // gzip压缩
      const productionGzipExtensions = ['html', 'js', 'css']
      config.plugins.push(
        new CompressionWebpackPlugin({
          filename: '[path].gz[query]',
          algorithm: 'gzip',
          test: new RegExp(
            '\\.(' + productionGzipExtensions.join('|') + ')$'
          ),
          threshold: 10240, // 只有大小大于该值的资源会被处理 10240
          minRatio: 0.8, // 只有压缩率小于这个值的资源才会被处理
          deleteOriginalAssets: false // 删除原文件
        })
      )
    }
    return {
      name: name,
      resolve: {
        alias: {
          '@': resolve('src')
        }
      },
      output: {
        filename: `[name].[hash].js`,
        chunkFilename: `[name].[hash].js`
      },
      externals: {
        'vue': 'Vue',
        'element-ui': 'Element',
        'echarts': 'echarts'
      }
    }
  },
  chainWebpack(config) {
    config.plugins.delete('preload') // TODO: need test
    config.plugins.delete('prefetch') // TODO: need test

    config.module
      .rule('geojson')
      .test(/\.geojson$/)
      .use('json-loader')
      .loader('json-loader')
      .end();

    // set svg-sprite-loader
    config.module
      .rule('svg')
      .exclude.add(resolve('src/icons'))
      .end()
    config.module
      .rule('icons')
      .test(/\.svg$/)
      .include.add(resolve('src/icons'))
      .end()
      .use('svg-sprite-loader')
      .loader('svg-sprite-loader')
      .options({
        symbolId: 'icon-[name]'
      })
      .end()

    // set preserveWhitespace
    config.module
      .rule('vue')
      .use('vue-loader')
      .loader('vue-loader')
      .tap(options => {
        options.compilerOptions.preserveWhitespace = true
        return options
      })
      .end()

    config
      // https://webpack.js.org/configuration/devtool/#development
      .when(process.env.NODE_ENV === 'development',
        config => config.devtool('cheap-source-map')
      )

    config
      .when(process.env.NODE_ENV !== 'development',
        config => {
          config
            .plugin('ScriptExtHtmlWebpackPlugin')
            .after('html')
            .use('script-ext-html-webpack-plugin', [{
              // `runtime` must same as runtimeChunk name. default is `runtime`
              inline: /runtime\..*\.js$/
            }])
            .end()
          config
            .optimization.splitChunks({
              chunks: 'all',
              cacheGroups: {
                libs: {
                  name: 'chunk-libs',
                  test: /[\\/]node_modules[\\/]/,
                  priority: 10,
                  chunks: 'initial' // only package third parties that are initially dependent
                },
                commons: {
                  name: 'chunk-commons',
                  test: resolve('src/components'), // can customize your rules
                  minChunks: 3, //  minimum common number
                  priority: 5,
                  reuseExistingChunk: true
                }
              }
            })
          config.optimization.runtimeChunk('single')
        }
      )
  }
}
module.exports = {
    // 配置输出目录
    outputDir: 'dist',
    // 配置静态资源目录
    assetsDir: 'assets',
    // 用于多页应用
    pages: {
        index: {
            // 入口文件
            entry: 'src/main.js',
            // 模板文件
            template: 'public/index.html',
            // 输出文件名
            filename: 'index.html'
        }
    }
}